// 定义页面的modal大小
function setModalSize() {
	var documentW = $(window).width();
	var documentH = $(window).height();
	$('#modalW').width(documentW * 0.7);
	$('#chart').width(documentW *0.680)
	$('#modalH,#chart').height(documentH * 0.8);
}


jQuery(document).ready(function() {
	$.ajax({
		async : false,
		url : projectPath + "user/getCurrentUser.do",
		data : {},
		dataType : "json",
		success : function(data) {
			$('#org').val(data.orgname);
			$('#org').attr('data', data.orgcode);
		}
	});

	initTable();
	App.setPage("tjauditor");  //Set current page
	App.init(); //Initialise plugins and elements
	bindItem("itemtypecode", null, null);
	//列表查询事件
	$('#search').click(function(){
		$('#table').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
	});
	
	checkboxChange();
	downChange();
	//绑定机构下拉列表
	bindOrg2('org');
	var dataList = null;
	$('#search').click(function(){
		if(validate()){
			var result = getData();
			dataList = result!=undefined?result.rows:null;
			if(dataList!=null){
				loadList(dataList);
				if(dataList.length>0){
					$('.disabled').each(function(index,e){
						$(this).removeClass('disabled');
					})
				}else{
					$('#btn a').each(function(index,e){
						$(this).addClass('disabled');
					})
				}
			}
		}
	});
	
	var date = new Date();      
	var time = date.Format("yyyy-MM-dd");
	$('input[type="date"]').each(function(){//限制时间只能选择当前时间或者以前
		 $(this).popover('hide');
		 $(this).attr("max",time);
	})
	qurterSelect();
	$('#lineChart,#barChart').click(function(){//统计图 模态窗
		setModalSize();
		if($(this).attr("id")=="lineChart"){
			$('#modalTile').html("折线图");
			if(dataList!=null)
				initChart('line',dataList);
		}else{
			$('#modalTile').html("柱状图");
			if(dataList!=null)
				initChart('bar',dataList);
		}
		$("#modal").modal('show');
	});
	
	$("[data-toggle='popover']").popover( {
		content:function(){
			return $('.popover-content').html(); 
		}
	});
});	


function hidePop(){//隐藏弹出框
	$("[data-toggle='popover']").popover('hide');
}
function exp(type, fn, dl) {//table导出
	$("[data-toggle='popover']").popover('hide');
	var elt = document.getElementById('table');
	var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
	return dl ?
		XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) :
		XLSX.writeFile(wb, fn || (getExcelFileName('审批统计')+'.' + (type || 'xlsx')));
}

function getExcelFileName(name) {  
    var d = new Date();  
    var curYear = d.getYear();  
    var curMonth = "" + (d.getMonth() + 1);  
    var curDate = "" + d.getDate();  
    var curHour = "" + d.getHours();  
    var curMinute = "" + d.getMinutes();  
    var curSecond = "" + d.getSeconds();  
    if (curMonth.length == 1) {  
        curMonth = "0" + curMonth;  
    }  

    if (curDate.length == 1) {  
        curDate = "0" + curDate;  
    }  

    if (curHour.length == 1) {  
        curHour = "0" + curHour;  
    }  

    if (curMinute.length == 1) {  
        curMinute = "0" + curMinute;  
    }  

    if (curSecond.length == 1) {  
        curSecond = "0" + curSecond;  
    }  
    var fileName = name + "_" + curYear + curMonth + curDate + "_"  
            + curHour + curMinute + curSecond;  
    return fileName;  

}  

function validate(){//查询输入参数校验
	var duration =$('#date2 div:visible').find('input[type="number"]').val();
	$('#date div:visible input[type="date"]').each(function(index,e){
		if($(this).val()==""){
			$(this).popover("show");
			 return false;
		}
	});
	if($('#date2 div:visible .input-date').val()==""){
		$('.input-date').popover("show");
		return false;
	}
	if(duration<1|| duration>3){
		console.log(	$('#date2 div:visible').find('input[type="number"]'))
		$('#date2 div:visible').find('input[type="number"]').popover("show");
		return false;
	} 
	return true;
}


function qurterSelect(){//季度格式化
	
	$.fn.datetimepicker.dates['zh-CN-qtrs'] = {
		    days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
		    daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
		    daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
		    months: ["第一季度", "第二季度", "第三季度", "第四季度", "", "", "", "", "", "", "", ""],
		    monthsShort: ["一季度", "二季度", "三季度", "四季度", "", "", "", "", "", "", "", ""],
		    clear: "清除",
		    meridiem: ["上午", "下午"]
   };
		
	//初始化选中当前季度
	var date = new Date();
	date.setDate(1);
	date.setMonth(Math.floor(date.getMonth() / 3));
	$('input.input-date').each(function() {
		    var that = $(this);
		    that.datetimepicker({
		        startView:3,
		        minView:3,
		        format:'yyyy/MM',
		        language:'zh-CN-qtrs',
		        initialDate: date,
		        endDate:date,
		        autoclose: 1
		    });
		    that.data('datetimepicker').picker.addClass('quarter');
	}); 
}


function downChange(){//季度月份下拉
	$('#date2 select').change(function(){
		var p1=$(this).children('option:selected').val();
		if("2" == p1){
			$('#month').attr('class',"hidden");
			$('#quarter').removeAttr('class');
		}else{
			$('#quarter').attr('class',"hidden");
			$('#month').removeAttr('class');
		}
	});
}

function checkboxChange(){//同比环比选择
	$(':checkbox').change(function(){
		var obj = $(this);
		$(':checkbox').each(function(){
			if($(obj).is(":checked")){
				$(obj).prop("checked",false);
			}else{
				$(':checkbox').prop("checked",false);
				$(obj).prop("checked",true);
			}
		});
		if("count1"==$(obj).attr('name')&&$(obj).is(":checked")){
			$('#date2').removeAttr('class');
			$('#date1').attr('class',"hidden");
		}else if("count2"==$(obj).attr('name')&&$(obj).is(":checked")){
			$('#date2').attr('class',"hidden");
			$('#date1').removeAttr('class');
			
		}else{
			$('#date2').attr('class',"hidden");
			$('#date1').removeAttr('class');
		}
		
	})
}

function loadList(data){
	 var columns =[];
	 var column = {};
	 column.field ="itemname";
	 column.title ="项目名称";
	 columns.push(column);
	 column = {};
	 column.field ="itemtype";
	 column.title ="项目类型";
	 columns.push(column);
	 for(var i=0;i<data.length;i++){
 		for(var key in data[i]){
 			 column = {
 					field: null,
 				    title: null
 			};
 			if(key!="itemname"&&key!="itemtype"){
 				column.field =key;
     			column.title =key;
     			columns.push(column);
 			}
 	    }
 		break;
 	}
 	$('#table').bootstrapTable('refreshOptions',{
 		columns:columns,
 		data:data
 	})
}


function getData(){//获取列表数据
	var result ;
	var param  = {
        	itemName: $("#itemtypecode").find("option:selected").text()!=""?$("#itemtypecode").find("option:selected").text():null,
        	endTime:null,
        	startTime:null,
        	duration:null,
        	type:null,
        	orgCode:$("#org").attr("data"),
        	flag:$(':checkbox:checked').val()==undefined?-1:$(':checkbox:checked').val()
        };
	
	 if("date1" ==$('#date div:visible').attr("id")){
		 param.startTime =  $('#date div:visible').find('input[type="date"]:eq(0)').val();
		 param.endTime =  $('#date div:visible').find('input[type="date"]:eq(1)').val();
	 }else{
		param.type =  $('#date div:visible select').find('option:selected').val();
		if(param.type==1){
			param.endTime =  $('#date2 div:visible').find('input[type="date"]').val();
			param.duration =  $('#date2 div:visible').find('input[type="number"]').val();
		}else{//季度
			var quarter   =  $('#date2 div:visible').find('input[type="text"]').val();  
			param.endTime =quarter.split('/')[0];
			if(quarter.split('/')[1]=="第一季度"){
				param.endTime +="-"+'03';
			}else if(quarter.split('/')[1]=="第二季度"){
				param.endTime +="-"+'06';
			}else if(quarter.split('/')[1]=="第三季度"){
				param.endTime +="-"+'09';
			}else{
				param.endTime +="-"+'12';
			}
			
			param.duration =  $('#date2 div:visible').find('input[type="number"]').val();
		}
	 }
	
	if(param.endTime!=""){
		$.ajax({
			method:'post',
			url: basePath() + 'statistics/auditorStatistics.do',
		    dataType: "json",
		    async: false,
		    data:JSON.stringify(param),
	        contentType: "application/json",
	        success:function(data){
	        	result = data;
	        }
		});
	} 

	return result;
}

function initTable(){	
	
	$('#table').bootstrapTable({
        striped: true,      //是否显示行间隔色
        sidePagination: "server",
	    columns:  [
	    	{filed:"itemname",title:"项目名称"},
	    	{filed:"itemtype",title:"项目类型"} 
	    	]
	});
}

function initChart(type,data){
	var myChart = echarts.init(document.getElementById('chart')); 
	  var rows = getData().rows;
	  var series  = [];
	  var legends =[];
	  var xAxis =[];
	  for(var i =0;i<data.length;i++){
		  for(var key in data[i]){
			 if(key!="itemname"&&key!="itemtype"){
				if($.inArray(key, legends)<0 ){
					legends.push(key);
				}
			 }
		  }
		xAxis.push(data[i].itemname );
	  }
	  for(var i = 0;i<legends.length;i++){//计算series
		  var serie = {
				  name:legends[i],
				  type:type,
				  data:[]
		  }
		  for(var j=0;j<data.length;j++){
			  serie.data.push(data[j][legends[i]]);
		  }
		  series.push(serie);
	  }
	  myChart.setOption({
		toolbox:{
			show:true,
			feature:{
				saveAsImage:{
					show:true,
					name:'审批统计',
					excludeComponents:['toolbox']
				}
			}
		},
      	tooltip: {
              show: true
          },
          legend: {
              data:legends
          },
          grid:{
        	  y2:200
          },
          xAxis : [
              {
                  type : 'category',
                  boundaryGap:[0,0.01],
                  data : xAxis,
                  axisLabel:{
                	  rotate:40,
                	  interval:0
                  }
              }
          ],
          yAxis : [
              {
                  type : 'value'
              }
          ],
          series : series
      }); 
}



/**时间格式化**/
Date.prototype.Format = function (fmt) {  
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
} 


 